package com.grant.code.controller;

import com.grant.code.Main;
import com.grant.code.pojo.User;
import com.grant.code.service.UserService;
import com.grant.code.service.VideoService;
import com.grant.code.utils.UIUtils;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.TilePane;
import javafx.stage.Modality;
import javafx.stage.StageStyle;
import org.springframework.beans.factory.annotation.Autowired;
import javafx.application.Platform;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * 主控制器 - 应用程序的中央控制器，协调各个功能控制器的工作
 * 主要负责初始化和协调其他控制器的工作，处理全局事件
 */
@FXMLController
public class MainController implements Initializable, FileTreeController.DirectorySelectedCallback {

    // 注入的服务
    @Autowired
    private UserService userService;
    
    @Autowired
    private VideoService videoService;

    // 添加ChatBotController引用
    @Autowired
    private ChatBotController chatBotController;

    // 拆分的控制器
    private UserController userController;
    private FileTreeController fileTreeController;
    private ImageController imageController;
    private VideoController videoController;
    private SlideShowController slideShowController;

    // FXML注入元素
    @FXML private TreeView<File> directoryTree;
    @FXML private TilePane imageContainer;
    @FXML private TilePane videoContainer;
    @FXML private Label lblWelcome;
    @FXML private Label directoryInfo;
    @FXML private Label selectionInfo;
    @FXML private Label statusBar;
    @FXML private HBox userInfoBar;
    @FXML private ImageView userAvatar;
    @FXML private TabPane mainTabPane;
    
    /**
     * JavaFX 初始化方法
     * @param location FXML的URL
     * @param resources 资源包
     */
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 初始化状态栏
        statusBar.setText("系统启动中...");
        
        // 检查userService是否为null，如果是，尝试手动获取
        if (userService == null) {
            System.err.println("警告: userService未被正确注入! 尝试手动获取...");
            try {
                // 尝试从Spring上下文中获取
                userService = Main.getContext().getBean(UserService.class);
                if (userService != null) {
                    System.out.println("userService手动获取成功!");
                } else {
                    System.err.println("手动获取userService失败!");
                    statusBar.setText("警告: userService获取失败!");
                }
            } catch (Exception e) {
                System.err.println("手动获取userService时出错: " + e.getMessage());
                e.printStackTrace();
                statusBar.setText("警告: userService获取出错!");
            }
        } else {
            System.out.println("userService已成功注入");
        }
        
        // 检查videoService是否为null
        if (videoService == null) {
            System.err.println("警告: videoService未被正确注入! 尝试手动获取...");
            try {
                videoService = Main.getContext().getBean(VideoService.class);
                if (videoService != null) {
                    System.out.println("videoService手动获取成功!");
                } else {
                    System.err.println("手动获取videoService失败!");
                    statusBar.setText("警告: videoService获取失败!");
                }
            } catch (Exception e) {
                System.err.println("手动获取videoService时出错: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("videoService已成功注入");
        }
        
        // 初始化各个控制器
        initializeControllers();
        
        // 确保视频列表刷新，显示拖放提示
        Platform.runLater(() -> {
            if (videoController != null) {
                videoController.refreshVideoList();
            }
        });
        
        // 更新状态栏
        statusBar.setText("系统就绪");
    }

    /**
     * 确保userService可用
     * @return 可用的UserService实例
     */
    private UserService ensureUserService() {
        if (userService == null) {
            try {
                userService = Main.getContext().getBean(UserService.class);
                if (userService != null) {
                    System.out.println("userService已成功获取");
                } else {
                    System.err.println("无法获取userService，可能影响部分功能");
                    statusBar.setText("警告: 用户服务未正确初始化，部分功能可能不可用");
                }
            } catch (Exception e) {
                System.err.println("获取userService时出错: " + e.getMessage());
                e.printStackTrace();
                statusBar.setText("警告: 用户服务初始化失败");
            }
        }
        return userService;
    }
    
    /**
     * 确保videoService可用
     * @return 可用的VideoService实例
     */
    private VideoService ensureVideoService() {
        if (videoService == null) {
            try {
                videoService = Main.getContext().getBean(VideoService.class);
                if (videoService != null) {
                    System.out.println("videoService已成功获取");
                } else {
                    System.err.println("无法获取videoService，可能影响视频功能");
                    statusBar.setText("警告: 视频服务未正确初始化，视频功能可能不可用");
                }
            } catch (Exception e) {
                System.err.println("获取videoService时出错: " + e.getMessage());
                e.printStackTrace();
                statusBar.setText("警告: 视频服务初始化失败");
            }
        }
        return videoService;
    }
    
    /**
     * 初始化和配置拆分后的控制器
     */
    private void initializeControllers() {
        try {
            // 确保服务可用
            UserService userServiceInstance = ensureUserService();
            VideoService videoServiceInstance = ensureVideoService();
            
            // 初始化用户控制器
            userController = new UserController(userServiceInstance, lblWelcome, userAvatar, statusBar);
            
            // 初始化文件树控制器
            fileTreeController = new FileTreeController(directoryTree, statusBar);
            fileTreeController.setDirectorySelectedCallback(this);
            
            // 初始化图片控制器
            imageController = new ImageController(imageContainer, directoryInfo, selectionInfo, statusBar);
            
            // 初始化视频控制器
            videoController = new VideoController(videoContainer, statusBar, videoServiceInstance, userServiceInstance);
            
            // 初始化幻灯片控制器
            slideShowController = new SlideShowController();
            
        } catch (Exception e) {
            statusBar.setText("初始化控制器失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 初始化应用数据
     * @param user 当前用户
     */
    public void initData(User user) {
        if (user == null) {
            statusBar.setText("错误: 用户数据为空");
            return;
        }
        
        try {
            // 设置当前用户
            userController.setCurrentUser(user);
            // 更新欢迎信息
            userController.updateWelcomeMessage();
            // 加载用户头像
            userController.loadUserAvatar();
            
            // 设置视频控制器的当前用户
            if (videoController != null) {
                videoController.setCurrentUser(user);
            }
            
            // 更新状态栏
            statusBar.setText("欢迎回来, " + user.getUserName());
        } catch (Exception e) {
            statusBar.setText("初始化用户数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 处理目录选择回调
     * @param directory 选中的目录
     */
            @Override
    public void onDirectorySelected(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            try {
                // 更新图片控制器的当前目录
                imageController.setCurrentDirectory(directory);
                
                // 更新状态栏
                statusBar.setText("已加载目录: " + directory.getAbsolutePath());
            } catch (Exception e) {
                statusBar.setText("加载目录失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 处理标签页切换事件
     */
    @FXML
    private void handleTabChange() {
        int selectedIndex = mainTabPane.getSelectionModel().getSelectedIndex();
        
        try {
            // 根据选中的标签页加载相应内容
            if (selectedIndex == 0) { // 图片标签页
                File currentDir = imageController.getCurrentDirectory();
                if (currentDir != null) {
                    // 确保图片加载功能已实现
                    // imageController.loadImagesFromDirectory(currentDir);
                }
            } else if (selectedIndex == 1) { // 视频标签页
                videoController.refreshVideoList();
            }
        } catch (Exception e) {
            statusBar.setText("切换标签页失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 处理头像点击事件，委托给用户控制器
     * @param event 鼠标事件
     */
    @FXML
    private void handleAvatarClick(MouseEvent event) {
        userController.handleAvatarClick(event);
    }
    
    /**
     * 处理目录点击事件，委托给文件树控制器
     * @param event 鼠标事件
     */
    @FXML
    private void handleDirectoryClick(MouseEvent event) {
        fileTreeController.handleDirectoryClick(event);
    }
    
    /**
     * 上传视频，委托给视频控制器
     */
    @FXML
    private void uploadVideo() {
        try {
            videoController.uploadVideo();
            } catch (Exception e) {
            statusBar.setText("上传视频失败: " + e.getMessage());
            showErrorDialog("上传视频", "无法上传视频", e.getMessage());
        }
    }
    
    /**
     * 刷新视频列表，委托给视频控制器
     */
    @FXML
    private void refreshVideoList() {
        try {
            videoController.refreshVideoList();
                } catch (Exception e) {
            statusBar.setText("刷新视频列表失败: " + e.getMessage());
        }
    }

    /**
     * 启动幻灯片播放，委托给图片控制器
     */
    @FXML
    private void startSlideShow() {
        if (imageController != null) {
            imageController.startSlideShow();
        } else {
            showErrorDialog("幻灯片播放", "错误", "图片控制器未初始化");
        }
    }
    
    /**
     * 退出系统
     */
    @FXML
    private void onExit() {
        // 确认退出
        if (showConfirmDialog("退出系统", "确认退出", "确定要退出系统吗？")) {
        Main.shutdown();
        }
    }

    /**
     * 显示关于对话框
     */
    @FXML
    private void showAbout() {
        showInfoDialog("关于系统", 
                "电子图片管理系统 v1.0\n\n" +
                "技术支持: JavaFX 17 + Spring Boot\n" +
                "开发者: Grant团队");
    }
    
    /**
     * 处理聊天机器人点击
     * @param event 鼠标事件
     */
    @FXML
    private void handleChatBotClick(MouseEvent event) {
        try {
            // 确保chatBotController已被初始化
            if (chatBotController == null) {
                chatBotController = Main.getContext().getBean(ChatBotController.class);
                if (chatBotController == null) {
                    throw new Exception("无法获取ChatBotController");
                }
            }
            
            // 设置当前用户
            if (userController != null && userController.getCurrentUser() != null) {
                String username = userController.getCurrentUser().getUserName();
                chatBotController.setCurrentUser(username);
            }
            
            // 显示聊天窗口
            chatBotController.showChatDialog();
            
            statusBar.setText("AI助手已启动");
        } catch (Exception e) {
            statusBar.setText("聊天组件加载失败: " + e.getMessage());
            showErrorDialog("AI助手", "无法加载聊天组件", e.getMessage());
        }
    }
    
    /**
     * 处理修图按钮点击
     */
    @FXML
    private void handleEditPhotoButton() {
        try {
            // 根据操作系统选择不同命令
            String os = System.getProperty("os.name").toLowerCase();
            String command;
            if (os.contains("win")) {
                command = "rundll32 url.dll,FileProtocolHandler " + "https://www.canva.cn/photo-editor/";
            } else if (os.contains("mac")) {
                command = "open " + "https://www.canva.cn/photo-editor/";
            } else if (os.contains("nix") || os.contains("nux")) {
                command = "xdg-open " + "https://www.canva.cn/photo-editor/";
            } else {
                showErrorDialog("图片编辑", "不支持的操作系统", "无法识别的操作系统");
                return;
            }
            
            Runtime.getRuntime().exec(command);
            statusBar.setText("已打开在线图片编辑器");
        } catch (Exception e) {
            statusBar.setText("无法打开图片编辑器: " + e.getMessage());
            showErrorDialog("图片编辑", "无法打开图片编辑器", e.getMessage());
        }
    }
    
    // 辅助方法，简化对话框调用
    
    private void showInfoDialog(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
    
    private void showErrorDialog(String title, String header, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }
    
    private void showWarningDialog(String title, String header, String content) {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }
    
    private boolean showConfirmDialog(String title, String header, String content) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        return alert.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK;
    }

    public void updateCurrentUser(User freshUser) {
        userController.updateCurrentUser(freshUser);
        userController.updateWelcomeMessage();
        userController.loadUserAvatar();
    }

    /**
     * 处理复制操作，委托给图片控制器
     */
    @FXML
    public void handleCopy() {
        try {
            imageController.handleCopy();
                } catch (Exception e) {
            statusBar.setText("复制失败: " + e.getMessage());
            showErrorDialog("复制操作", "复制失败", e.getMessage());
        }
    }

    /**
     * 处理粘贴操作，委托给图片控制器
     */
    @FXML
    public void handlePaste() {
        try {
            imageController.handlePaste();
        } catch (Exception e) {
            statusBar.setText("粘贴失败: " + e.getMessage());
            showErrorDialog("粘贴操作", "粘贴失败", e.getMessage());
        }
    }

    /**
     * 处理删除操作，委托给图片控制器
     */
    @FXML
    public void handleDelete() {
        try {
            imageController.handleDelete();
        } catch (Exception e) {
            statusBar.setText("删除失败: " + e.getMessage());
            showErrorDialog("删除操作", "删除失败", e.getMessage());
        }
    }

    /**
     * 处理重命名操作，委托给图片控制器
     */
    @FXML
    public void handleRename() {
        try {
            imageController.handleRename();
        } catch (Exception e) {
            statusBar.setText("重命名失败: " + e.getMessage());
            showErrorDialog("重命名操作", "重命名失败", e.getMessage());
        }
    }
}